/**
 * 
 */
package com.jzcodecheck.ui.core.processor.codescan;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.autoscript.ui.helper.FileCtrlUtils;
import com.jzcodecheck.ui.core.BatchUI;

/**
 * @author ASUS
 * 代码注释扫描处理
 */
public class CodeNoteScanProcessor {
	private BatchUI ui;

	public CodeNoteScanProcessor(BatchUI ui) {
		this.ui = ui;
	}
	
	/**
	 * 扫描指定目录下的代码注释
	 * @param path 目录
	 * @return 
	 * @throws Exception
	 */
	public List<CodeNoteScanVo> doScan(String path) throws Exception{
		String[] extensions={"java"};
		Collection files = FileCtrlUtils.listFiles(new File(path), extensions, true);
		List<File> listFile = new ArrayList<File>();
		if(files==null||files.size()==0){
			throw new Exception("没有文件!");
		}
		listFile.addAll(files);
		List<CodeNoteScanVo>  resultVos = new ArrayList<CodeNoteScanVo>();
		String msg="";
		ui.addOutputMessage("开始扫描...");
		for(int i=0;i<listFile.size();i++){			
			resultVos.add(scanFile(listFile.get(i)));
			ui.addOutputMessage(msg.format("统计文件：%s结束.", listFile.get(i)));
		}
		ui.addOutputMessage("扫描完成!");
		return resultVos;
	}
	/**
	 * 扫描单个文件
	 * @param fileName
	 * @return 扫描结果 
	 */
	private CodeNoteScanVo scanFile(File f) {
		BufferedReader br = null;
		boolean comment = false;
		long whiteLines=0L;//空白行
		long commentLines=0L;//注释行
		long normaiLines =0L;//实际代码行数
		try {
			br = new BufferedReader(new FileReader(f));
			String line = "";
			while ((line = br.readLine()) != null) {
				line = line.trim();
				if (line.matches("^[//s&;&;[^//n]]*$")) {
					
					whiteLines++;
				} else if (line.startsWith("/*") && !line.endsWith("*/")) {
					commentLines++;
					comment = true;
				} else if (true == comment) {
					commentLines++;
					if (line.endsWith("*/")) {
						comment = false;
					}
				} else {
					normaiLines++;
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
					br = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		CodeNoteScanVo vo = new CodeNoteScanVo();
		vo.setFileName(FileCtrlUtils.getFileName(f.getAbsolutePath()));
		vo.setNormaiLines(normaiLines);
		vo.setWhiteLines(whiteLines);
		vo.setCommentLines(commentLines);
		vo.setPath(FileCtrlUtils.getFilePath(f.getAbsolutePath()));
		vo.setNotePercent((commentLines*100)/(commentLines+whiteLines+normaiLines));
		
		return vo;
		
	}
}
